import 'dart:convert';

import 'package:flutter_component_tool/flutter_components_tools.dart';
import 'package:flutter_multi_environment/env_config.dart';
import 'package:flutter_native_plugins/flutter_native_plugins.dart';

String? userToken;

/// Mark ----- 封装基础网络请求工具类
enum MethodType {
  get,
  post,
}

class WkHttps {
  /// 创建单例
  /* static WkHttps? _instance;
  WkHttps._internal() {
    /// 初始化某些需要初始化的东西
  }
  // factory WkHttps() => _instance ??= HttpsUtls._internal();
  HttpsUtls get shared => _instance ??= HttpsUtls._internal(); */

  ///
  /// Post 请求
  ///
  /// * [url] 地址
  ///
  /// * [parameters] 请求参数
  ///
  static Future<BaseResponseModel> post(
    String url, {
    Map<String, dynamic>? parameters,
  }) {
    return BaseRequestExtension._commonRequest(url, type: MethodType.post, parameters: parameters);
  }

  ///
  /// Get 请求
  ///
  /// * [url] 地址
  ///
  /// * [parameters] 请求参数
  ///
  static Future<BaseResponseModel> get(
    String url, {
    Map<String, dynamic>? parameters,
  }) {
    return BaseRequestExtension._commonRequest(url, type: MethodType.get, parameters: parameters);
  }
}

extension BaseRequestExtension on WkHttps {
  static final CNMHttpsPlugins _cnmHttpsPlugins = CNMHttpsPlugins();

  ///
  /// 公共请求函数
  ///
  /// * [url] 地址
  ///
  /// * [type] 请求类型
  ///
  /// * [parameters] 请求参数
  ///
  static Future<BaseResponseModel> _commonRequest(
    String url, {
    required MethodType type,
    Map<String, dynamic>? parameters,
  }) async {
    Map<String, String> headers = {};
    Map? result;
    Map? data;
    BaseResponseModel responseModel = BaseResponseModel(
      code: -1,
      msg: '抱歉，请求失败',
      succ: false,
      data: null,
    );

    /// 头部配置
    if (userToken != null) {
      headers["i84-ssps-Token-app"] = userToken ?? '';
    }

    /// 拼接url
    String uri = '${EvnConfig.curEvn.domain}$url';

    if (type == MethodType.get) {
      try {
        result = await _cnmHttpsPlugins.cnmGet(
          uri,
          parameters: parameters,
          headers: headers,
        );
      } on TypeError catch (e, s) {
        print('get 捕获异常：$e \n 以及Stack：$s');
      }
    } else if (type == MethodType.post) {
      try {
        result = await _cnmHttpsPlugins.cnmPost(
          uri,
          parameters: parameters,
          headers: headers,
        );
      } on TypeError catch (e, s) {
        print('post 捕获异常：$e \n 以及Stack：$s');
      }
    }

    if (result == null) return responseModel;

    /// 外层原生模型
    BaseRequestNativeModel nativeModel = BaseRequestNativeModel.fromMap(result);

    if (nativeModel.errorCode != 0) {
      responseModel
        ..code = nativeModel.errorCode
        ..msg = nativeModel.errorMessge
        ..succ = false
        ..data = null;
    }

    /// 响应数据模型
    if (!CNMUtils.isBlank(nativeModel.data)) {
      data = jsonDecode(nativeModel.data!); // 解析数据源
    }
    responseModel = BaseResponseModel.fromJson(data);

    return responseModel;
  }
}

///
/// 请求最外层原生包裹模型
///
class BaseRequestNativeModel {
  /// 请求响应 code（成功返回0）
  final int? errorCode;

  /// 请求响应失败文本
  final String? errorMessge;

  /// 请求响应 data
  final String? data;

  BaseRequestNativeModel({
    this.errorCode,
    this.errorMessge,
    this.data,
  });

  factory BaseRequestNativeModel.fromMap(Map json) => BaseRequestNativeModel(
        errorCode: json["error_code"] ?? -1,
        errorMessge: json["error_message"] ?? '抱歉请求失败',
        data: json["success_data"],
      );
}

/// 请求响应数据模型
class BaseResponseModel {
  /// 响应返回 code
  int? code;

  /// 响应返回时长
  final String? executeTime;

  /// 响应返回数据正确/失败文本
  String? msg;

  /// 响应返回数据是否成功
  bool? succ;

  /// 响应返回数据
  dynamic data;

  BaseResponseModel({
    this.code,
    this.executeTime,
    this.msg,
    this.succ,
    this.data,
  });

  factory BaseResponseModel.fromJson(Map? json) => BaseResponseModel(
        code: json?["code"],
        executeTime: json?["executeTime"],
        msg: json?["msg"],
        succ: json?["succ"],
        data: json?["data"],
      );
}
